package com.bazaaroid.client.web.gwt.clientmodule.client;

import java.util.HashSet;
import java.util.Set;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.http.client.RequestBuilder.Method;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;

public class BazaaroidRestService {

	private static final String bazaaroidBetaURL = "http://beta-bazaaroid.appspot.com/rest/";
	private static RequestBuilder request;
	
	private static RequestBuilder createJSONRequest(Method method, String url) {
		RequestBuilder request = new RequestBuilder(method, url);
		request.setHeader("Content-type","application/json; charset=utf-8");
	    return request;
	}
	
	public static Set<String> getCategories() {
		final Set<String> categories = new HashSet<String>();
		String url = bazaaroidBetaURL + "category/all";
		System.out.println("url: " + url);
		request = createJSONRequest(RequestBuilder.GET, url);
		
		try {
			request.sendRequest(null, new RequestCallback() {
				
				@Override
				public void onResponseReceived(Request request, Response response) {
					if (200 == response.getStatusCode()) {
						System.out.println("response: " + response.getText());
			            JSONObject json = (JSONObject) JSONParser.parse(response.getText());
			            JSONObject jsonRoot = (JSONObject) json.get("categories");
			            JSONArray jsonCategories = (JSONArray) jsonRoot.get("category");
			            for(int i=0; i<jsonCategories.size(); i++) {
			            	JSONObject jsonCategory = (JSONObject) jsonCategories.get(i); 
			            	categories.add(jsonCategory.get("name").toString());
			            }
			            	
			          } else {
			        	  System.out.println("RestService getCategories error: " + response.getStatusCode() + ' ' + response.getStatusText());
			          }
				}
				
				@Override
				public void onError(Request request, Throwable exception) {
					System.out.println("RestService getCategories error");
					
				}
			});
		} catch (RequestException e) {
			e.printStackTrace();
		}
		
		return categories;		
	}
}
